package com.zjmzxfzhl.modules.flowable.util;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.io.IOUtils;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;

/**
 * 项目文件操作工具类
 *
 * @author wangxian 2020/11/9
 */
public class ProjectFileUtils {

    public static void downloadProjectFile(HttpServletResponse response, InputStream inputStream, String fileName) throws IOException {
        ServletOutputStream outputStream = response.getOutputStream();
        response.setContentType("multipart/form-data");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
        IOUtils.copy(inputStream, outputStream);
        outputStream.flush();
        outputStream.close();
    }

    public static void dynamicTemplateDownload(HttpServletResponse response, List<Map<String,String>> fieldList, String fileName) throws Exception {
        if(CollectionUtils.isEmpty(fieldList)) {
            throw new RuntimeException("模板头部不能为空，请先新增表单数据");
        }
        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet("导入模板");
        sheet.setDefaultColumnWidth(18);
        sheet.setColumnWidth(0, 20 * 256);
        int rowNo = 0;
        HSSFRow row = null;
        HSSFRow rowOne = null;
        HSSFCell cell = null;
        HSSFCell cellOne = null;
        row = sheet.createRow(rowNo++);
        rowOne = sheet.createRow(1);
        row.setHeight((short) 400);
        rowOne.setHeight((short) 400);
        for (int i = 0; i < fieldList.size(); i++) {
            Map<String, String> stringStringMap = fieldList.get(i);
            cell = row.createCell(i);
            cell.setCellValue(stringStringMap.get("label"));
            cellOne = rowOne.createCell(i);
            cell.setCellStyle(getCellStyle(HSSFColor.HSSFColorPredefined.LIGHT_GREEN.getIndex(), workbook));
            cellOne.setCellValue(stringStringMap.get("__vModel__"));
        }

        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName);
        OutputStream out = response.getOutputStream();
        workbook.write(out);
        out.close();
    }

    private static CellStyle getCellStyle(short index, Workbook workbook) {

        CellStyle cellStyle = workbook.createCellStyle();
        cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        cellStyle.setAlignment(HorizontalAlignment.CENTER);
        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        cellStyle.setFillForegroundColor(index);
        return cellStyle;
    }

}
